﻿using InhollandAir.App_Code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace InhollandAir
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btn_Login_Click(object sender, EventArgs e)
        {
            //login
            User user = new User();
            try
            {
                try
                {
                    user.Login(txt_username.Text, txt_password.Text);
                }
                catch (Exception ex)
                {
                    Tools.WaitAFewSeconds(1);
                    lbl_LoginException.Text = ex.Message;
                    lbl_LoginException.Visible = true;
                    return;
                }
                
            
                //user login succeed, now save user data in cache
                
                //get active users from server cache
                Dictionary<string, User> ActiveUserCache = (Dictionary<string, User>)Application["ActiveUsers"];

                SessionIDManager Manager = new SessionIDManager();

                string NewID = Manager.CreateSessionID(Context);                
                bool redirected = false;
                bool IsAdded = false;
                Manager.SaveSessionID(Context, NewID, out redirected, out IsAdded);
                //save session nr and user information server side in cache                
                ActiveUserCache.Add(NewID, user);
                Application["ActiveUsers"] = ActiveUserCache;

                //log user logged in
                Logging.WriteActivity("UserID: " + user.id + " logged in.");

                if (Request.Cookies["PendingFlightSearch"] != null)
                {
                    Response.Redirect("FlightReservations.aspx");
                }
                else
                {
                    Response.Redirect("Index.aspx");
                }
            }
            catch(Exception ex)
            {
                //user login failed
                //log exception
                Logging.WriteError(ex.Message + ". Username: " + txt_username);
                lbl_LoginException.Text = "Failed to login, please contact the admin.";
                lbl_LoginException.Visible = true;
            }
            
        }
    }
}